import os,time

# 记录文件路径
user_path = os.path.abspath('.')+'\\user.txt'
history_path = os.path.abspath('.') + '\\history.txt'

# 读取用户信息放入列表中
user_file = open(user_path)
user_list = user_file.readlines()

# 记录某条用户信息的下标
login_index = -1

# 检查一个用户名是否存在，存在返回下标，不存在返回-1
def check_name(name):
    for i in range(1, len(user_list)):
        if user_list[i].split(',')[0] == name:
            return i
    return -1

# 检查手机号是否有效
def check_phone(phone):
    isphone = True
    if len(phone) > 11:
        isphone = False
    for i in range(0,len(phone)):
        if ord(phone[i]) < 48 or ord(phone[i]) > 57:
            isphone = False
            break
    if isphone == False:
        return False
    else:
        return True

# 判断一个字符串能否被转换为一个有效的数字
def check_number(string):
    point = 0
    isvalid = True
    for c in string:
        code = ord(c)
        if (code < 48 and code != 46) or code > 57:
            isvalid = False
            break
        elif code == 46:
            point += 1
    if point > 1: isvalid = False
    return isvalid

# 注册
def reg():
    name = input("[注册]请输入用户名：")
    pwd = input("[注册]请输入密码：")
    phone = input("[注册]请输入手机号码：")
    if check_name(name) >= 0 or check_phone(phone) == False:
        print("用户信息输入不正确")
        reg()
    else:
        print("注册成功！")
        user_info = ''
        user_info += name + ','
        user_info += pwd + ','
        user_info += phone + ','
        user_info += '0' + '\n'
        user_file = open(user_path,mode='a+')
        user_file.writelines(user_info)
        user_file.close()
        start_menu()

# 登录
def login():
    name = input("[登录]请输入用户名：")
    pwd = input("[登录]请输入密码：")
    index = check_name(name)
    if index >= 0:
        if user_list[index].split(',')[1] == pwd:
            print("登录成功")
            global login_index
            login_index = index
            main_menu()
        else:
            print("密码错误")
            login()
    else:
        print("用户名错误")
        login()

# 账户金额的操作
def change_balance(account_index, money):
    current_list = user_list[account_index].split(',')
    name = current_list[0]
    pwd = current_list[1]
    phone = current_list[2]
    balance = current_list[3]
    balance = str(float(balance) + money)
    user_list[account_index] = name + ',' + pwd + ',' + phone + ',' + balance + '\n'
    file = open(user_path , mode='w')
    file.writelines(user_list)
    file.close()

# 查询
def query():
    balance = user_list[login_index].strip().split(',')[3]
    phone = user_list[login_index].split(',')[2]
    print(f'当前余额为：{balance},手机号码为：{phone}')
    main_menu()

# 取款
def withdraw():
    money = input("请输入你的取款金额：")
    balance = float(user_list[login_index].strip().split(',')[3])
    if check_number(money) and float(money) <= balance and float(money) % 100 == 0:
        change_balance(login_index,float(money) * -1)
        balance = float(user_list[login_index].strip().split(',')[3])
        print("成功取款%s，剩余金额%f" % (money, balance))
        save_history(login_index,'expend', money)
        main_menu()
    else:
        print("取款金额有误")
        withdraw()

# 存款
def deposite():
    money = input("请输入你的存款金额：")
    if check_number(money) and float(money) % 100 == 0:
        change_balance(login_index, float(money))
        balance = float(user_list[login_index].strip().split(',')[3])
        print("成功存款%s，剩余金额%s" % (money, balance))
        save_history(login_index, 'income', money)
        main_menu()
    else:
        print("存款金额有误")
        deposite()

# 转账
def transer():
    account = input("请输入你的转账账号：")
    account_index = check_name(account)
    if account_index >= 0 and account_index != login_index:
        money = input("请输入你的转账金额：")
        if check_number(money):
            money = float(money)
            balance = float(user_list[login_index].split(',')[3])
            if money <= balance:
                change_balance(login_index, float(money) * -1)
                balance = float(user_list[login_index].split(',')[3])
                print(f"转账成功！当前余额为：{balance}")
                change_balance(account_index, float(money))
                account_balance = float(user_list[account_index].split(',')[3])
                print(f"另一个账户余额为：{account_balance}")  # 方便检查另一个账户是否有进账
                save_history(login_index, 'expend', money)
                save_history(account_index, 'income', money)
            else:
                print("余额不足")
                transer()
        else:
            print("你输入的金额不符合规范")
            transer()
    elif account == login_index:
        print("你输入的账号为当前账号")
        transer()
    else:
        print("你输入的账号不存在")
        transer()
    main_menu()

# 保存流水记录
def save_history(account_index,op_type,money):
    user_info=user_list[account_index].split(',')
    this_history = user_info[0] + ',' + time.strftime('%Y-%m-%d %H:%M:%S')+ ',' + op_type+ ',' + str(money) + '\n'
    file = open(history_path, mode = 'a+')
    file.writelines(this_history)
    file.close()

# 流水
def history():
    file = open(history_path)
    history_list = file.readlines()
    history_index = []
    for i in range(0, len(history_list)):
        if history_list[i].split(',')[0] == user_list[login_index].split(',')[0]:
            history_index.append(i)
    if history_index == []:
            print('当前用户流水信息为空')
    else:
        print_history = []
        for j in history_index:
            print_list = history_list[j]
            print(print_list.split(','))
    main_menu()

# 修改密码
def update_pwd():
    while '1' == '1':
        new_pwd1 = input("请输入新密码：")
        new_pwd2 = input("请重复输入新密码：")
        if new_pwd1 == new_pwd2:
            break
    current_list = user_list[login_index].split(',')
    name = current_list[0]
    pwd = current_list[1]
    phone = current_list[2]
    balance = current_list[3]
    pwd = new_pwd1
    user_list[login_index] = name + ','+ pwd + ','+ phone + ','+ balance
    file = open(user_path , mode='w')
    file.writelines(user_list)
    file.close()
    print("修改密码成功")
    main_menu()

# 开始菜单
def start_menu():
    tip = '''
********************* 欢迎来到蜗牛ATM *********************
********************** 请选择以下操作 *********************
****************** 1.注册  2.登录  3.退卡 *****************         
    '''
    print(tip)
    option = input("请输入你的选择：")
    if option == '1':
        reg()
    elif option == '2':
        login()
    elif option == '3':
        exit("退卡成功")

# 主菜单
def main_menu():
    tip = '''
***************************** 进入蜗牛ATM主菜单 *****************************
****************************** 请选择以下操作 *******************************
******************* 1. 查询   2. 取款   3. 存款   4. 转账 *******************
****************** 5. 流水  6. 修改密码   7. 返回   8. 退卡 *****************     
        '''
    print(tip)
    option = input("请输入你的选择：")
    if option == '1':
        query()
    elif option == '2':
        withdraw()
    elif option == '3':
        deposite()
    elif option == '4':
        transer()
    elif option == '5':
        history()
    elif option == '6':
        update_pwd()
    elif option == '7':
        start_menu()
    elif option == '8':
        exit('谢谢，欢迎下次光临.')
    else:
        main_menu()



start_menu()